# Create your views here.

from django.shortcuts import render_to_response
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.contrib.auth import logout
from market.authentification import authentificatePlayer, authentificateUser
from django.template import RequestContext
from market.models import UserProfile, BetRoom, Player, WebSiteComment
from market.jsonsForCharts import getComments
from market.cometHelper import getChatRoomPlayerStatus
from market.models import BetRoom, MarketPlacePlayerMarketUpToDateStatus, ChatRoomPlayerUpToDateStatus
from market.exceptionHandler import handleRequestPlayerPOSTWithExceptionWhenNotSuspended
from market.exceptionHandler import handleRequestUserPOSTWithException
from django.utils import simplejson
from django.contrib.auth.tokens import default_token_generator
from django.contrib.sites.models import Site
from django.core.mail import send_mail
from django.template import loader
from django.template.context import Context
from django.utils.http import int_to_base36
import re


###########################################################################################
# return the page with the rules and the explanation
def logoutView(request):
        logout(request)
        return HttpResponseRedirect( "/market/" )


################################################################################################################
# get the betroom name from the request, declare that it is the last visited and return  
def enterBetroom0( request, user ):
        # get and check the asset name
        try:
                betroomName = request.POST["betroom"]
                betroom = BetRoom.objects.get( name = betroomName )
        except BetRoom.DoesNotExist:
                raise StupidUserException('There is no bet room called: ' +  betroomName + ". Nothing done!" )

        # enter the bet room
        up = user.get_profile()
        up.nameOfTheLastVistedBetRoom = betroomName
        up.save()
        return HttpResponse( '0', mimetype='application/javascript')

###########################################################################################
# implementation of rules 2 : the player change his strategy submitting a new one
# this is "part 1" where the new strategy is extract from the post request
def enterBetroom(request):
        return handleRequestUserPOSTWithException(  globals()["enterBetroom0"], request )


###########################################################################################
# send a email too the user for him to reset his password
def reset_password(request):
        alternative_response_list = [] #the answer to return if the player could not be authentificated with a dummy initialisation
        if not( authentificateUser( request, alternative_response_list ) ):
                return alternative_response_list[0]

        """Reset users password"""
        if not request.user.email:
                return render_to_response(
                'home/settings.html',
                {'userName':request.user.username, 'reset_psw_msg':'No email adress is attachet to your account. Please contact admin.' },
                context_instance=RequestContext(request) )

        t = loader.get_template('registration/password_reset_email.html')
        c = {
                'email': request.user.email,
                'domain': Site.objects.get_current().domain,
                'site_name': Site.objects.get_current().name,
                'uid': int_to_base36(request.user.id),
                'user': request.user,
                'token': default_token_generator.make_token(request.user),
                'protocol': 'http'
            }
        send_mail( ("Your account for %s") % Site.objects.get_current().name, t.render(Context(c)), None, [request.user.email])
        
        return render_to_response(
                'home/settings.html',
                {
                        'userName': request.user.username,
                        'user_email': request.user.email,
                        'reset_psw_msg':'A mail has been sent to ' + request.user.email +'. Please check your mail box and follow the instructions',
                        'reset_email_msg': '',
                        'send_me_email': request.user.get_profile().sendMeEmails
                },
                context_instance=RequestContext(request) )

###########################################################################################
# basic check for an email format
def validateEmail(email):
	if len(email) > 7:
		if re.match("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$", email) != None:
			return True
	return False

###########################################################################################
# send a email too the user for him to reset his password
def setNewEmail(request):
        
        alternative_response_list = [] #the answer to return if the player could not be authentificated with a dummy initialisation
        if not( authentificateUser( request, alternative_response_list ) ):
                return alternative_response_list[0]

        email_tmp = request.POST.get( 'new_email', '')

        # proceed if empty (skip request) or rekognised  as an email address
        if (email_tmp == '') or validateEmail(email_tmp):
                if email_tmp != '':
                        request.user.email = email_tmp
                        request.user.save()
                return render_to_response(
                        'home/settings.html',
                        {
                                'userName':request.user.username,
                                'user_email': request.user.email,
                                'reset_psw_msg':'',
                                'reset_email_msg': '',
                                'send_me_email': request.user.get_profile().sendMeEmails
                        },
                        context_instance=RequestContext(request) )
        else :
                return render_to_response(
                        'home/settings.html',
                        {
                                'userName':request.user.username,
                                'user_email': request.user.email,
                                'reset_psw_msg':'',
                                'reset_email_msg': email_tmp + ' has not been recognized as an email address.',
                                'send_me_email': request.user.get_profile().sendMeEmails
                        },
                        context_instance=RequestContext(request) )
                
###########################################################################################
# says if the user will receive emails
def setSendEmail0(request, user):
        user.get_profile().sendMeEmails = ( request.POST.get( 'check_send_email', 'true').lower() == 'true' )
        user.get_profile().save()
        return HttpResponse('0')

###########################################################################################
# says if the user will receive emails


def setSendEmail(request):
        return handleRequestUserPOSTWithException(  globals()["setSendEmail0"], request )


###########################################################################################
# suppress the asset per strategy when they are useless
def postComment(request):
        # authentification
        player_list = [] #the player with a dummy initialisation
        alternative_response_list = [] #the answer to return if the player could not be authentificated with a dummy initialisation
        if not( authentificatePlayer( request, player_list, alternative_response_list ) ):
                return alternative_response_list[0]
        p = player_list[0]
        
        text = request.POST["commentText"]
        
        # the browser is ignoring \n
        if text != "":
                text = text.replace('\n', '<br>')
                wsc = [ c for c in WebSiteComment.objects.filter(poster__mainStrategy__betroom = p.dbPlayer.mainStrategy.betroom)] 
                # we set the id number to the last id number + 1
                c = WebSiteComment(poster = p.dbPlayer, textValue = text )
                c.save()

        # update other player status
        for pdb in Player.objects.filter(mainStrategy__betroom = p.dbPlayer.mainStrategy.betroom):
                if pdb != p.dbPlayer:
                        playerStatus = getChatRoomPlayerStatus( pdb )
                        playerStatus.isUpToDateStatusForTheChat = False
                        playerStatus.save()
                        
        return HttpResponse(simplejson.dumps( [getComments(request)] ), mimetype='application/javascript')

###########################################################################################
# suppress the asset per strategy when they are useless
def hideComment(request):
        # authentification
        player_list = [] #the player with a dummy initialisation
        alternative_response_list = [] #the answer to return if the player could not be authentificated with a dummy initialisation
        if not( authentificatePlayer( request, player_list, alternative_response_list ) ):
                return alternative_response_list[0]
        p = player_list[0]

        try:
                c = WebSiteComment.objects.get( id__exact = request.POST["idNumber"] )
                c.isVisible = False;
                c.save()
        except:
                raise Exception( "hideComment: bad call" )
                
        # update other player status
        for pdb in Player.objects.filter(mainStrategy__betroom = p.dbPlayer.mainStrategy.betroom):
                if pdb != p.dbPlayer:
                        playerStatus = getChatRoomPlayerStatus( pdb )
                        playerStatus.isUpToDateStatusForTheChat = False
                        playerStatus.save()
                        
        return HttpResponse(simplejson.dumps( [getComments(request)] ), mimetype='application/javascript')



       

        

